<?php

namespace App\Library;

use App\Models\Admin\Picture;
use App\Models\video\DebugModel;
use Illuminate\Support\Str;

class UpTools
{
    // 字段名转驼峰
    public static function transferFields($data){
        if(empty($data)){
            return [];
        }
        if(is_array($data)){
            $newData = [];
            foreach ($data as $k => $v){
                if(is_array($v)){
                    $v = self::transferFields($v);
                }
                $newData[Str::camel($k)] = $v;
            }
            return $newData;
        }else{
            return Str::camel($data);
        }
    }

    /*curl 请求*/
    public static function curlRequest($requestArgs, $requestUrl, $timeout = 30,$type="GET")
    {
        $dataUrlParam = http_build_query($requestArgs, "", "&");
        if($type=="POST"){
            $url = $requestUrl  ;
            return self::curl($url, $dataUrlParam, $timeout);
        }
        else{
            $url = $requestUrl ."?". $dataUrlParam;
            return self::curl($url, null, $timeout);
        }
    }

    public static function curl($url, $data = null, $header = ['Content-Type: application/json'], $timeout = 60)
    {
        $ch = curl_init($url);
        if(empty($data)){
            curl_setopt($ch, CURLOPT_HTTPGET, 1);
        }else {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        if(!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $output = curl_exec($ch);
        $errno = curl_errno($ch);
        if ($errno) {
            $info  = curl_getinfo( $ch );
            $info['errno'] = $errno;
            curl_close($ch);
            self::writeLog("错误码：{$errno}--执行curl出错（错误原因查询:http://curl.haxx.se/libcurl/c/libcurl-errors.html）：".var_export($info,true), "curlError.txt");
            return false;
        }
        curl_close($ch);
        return $output;
    }

    /*生成GUID*/
    public static function createGUID()
    {
        if (function_exists('com_create_guid') === true)
        {
            return strtolower(str_replace("-","",trim(com_create_guid(), '{}')));
        }
        return strtolower(sprintf('%04X%04X%04X%04X%04X%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535)));
    }

    // 获取客户端ip地址
    public static function get_client_ip($type = 0)
    {
        $ip = '0.0.0.0';
        if (isset($_SERVER['HTTP_CLIENT_IP'])){
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED'];
        }
        else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_FORWARDED_FOR'];
        }
        else if (isset($_SERVER['HTTP_FORWARDED'])) {
            $ip = $_SERVER['HTTP_FORWARDED'];
        }
        else if (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $IPAddressNum = sprintf("%u",ip2long($ip));
        $ip   = $IPAddressNum ? array($ip, $IPAddressNum) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    // 点播媒体类型
    public static function vodMediaType(){
        return [
            'MP4', 'TS', 'FLV', 'WMV', 'ASF', 'RM', 'RMVB', 'MPG', 'MPEG', '3GP', 'MOV', 'WEBM', 'MKV', 'AVI',
            'MP3', 'M4A', 'FLAC', 'OGG', 'WAV', 'JPG', 'JPEG', 'PNG', 'GIF', 'BMP', 'TIFF', 'AI', 'CDR', 'EPS'
        ];
    }

    public static function getFileType($filePath)
    {
        if (empty($filePath)) {
            return '';
        }
        $tmp = explode("/", $filePath);
        $fullFileName = end($tmp);
        if (strrpos($fullFileName, ".") === false) {
            return '';
        }
        $pathArr = explode(".", $filePath);
        return end($pathArr);
    }

    // 创建目录
    static function mkdir($path) {
        if (!is_dir($path)) {
            self::mkdir(dirname($path));
            mkdir($path);
        }
        return true;
    }

    public static function writeLog($text = '', $filePath = '', $cover = false){
        global $scf_data;
        if(!empty($scf_data["host"])) {
            DebugModel::query()->insert(["content" => $text, "create_time" => time()]);
            DebugModel::query()->where([["create_time", "<=", strtotime("-6 month")]])->delete(); // 删除6个月前的日志
        }else {
            if (empty($filePath)) {
                $filePath = base_path() . "/public/operateLog/log.txt";
            }
            if (strpos($filePath, base_path()) === false) {
                $filePath = base_path() . "/public/operateLog/{$filePath}";
            }
            if ($cover && is_file($filePath)) {
                unlink($filePath);
            }
            self::mkdir(dirname($filePath));
            if (is_file($filePath) && 2097152 <= filesize($filePath)) { // 自动备份到 根目录的runtime/toolsLog/ 下
                try {
                    self::mkdir(base_path() . "/public/operateLog/back");
                    rename($filePath, base_path() . "/public/operateLog/back/" . time() . '-' . basename($filePath));
                } catch (\Exception $e) {
                }
            }
            $log = fopen($filePath, "a");        //记录分割的信息的文本文件
            fwrite($log, date("Y-m-d H:i:s") . "Tools记录调试日志：" . $text . "\r\n");
            fclose($log);
        }
    }

    public static function handleTimeToText($time){
        if(!is_numeric($time)){
            $time = strtotime($time);
        }
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        if($beginToday <= $time){ // 今天内
            if(($difference = floor((time() - $time) / 3600)) > 0){
                return "{$difference}小时前";
            }else{
                $difference = floor((time() - $time) / 60);
                return $difference > 0 ? "{$difference}分钟前" : "刚刚";
            }
        }elseif($beginToday - $time <= 86400){ // 昨天
            return "昨天";
        }elseif(mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")) <= $time){ // 本周
            return "本周";
        }else{
            return date("Y-m-d", $time);
        }
    }

    public static function getRgba($hexString){
        $hex = ltrim($hexString, '#'); // Remove #
        if(strlen($hex) == 3) {
            $r = hexdec(substr($hex,0,1).substr($hex,0,1));
            $g = hexdec(substr($hex,1,1).substr($hex,1,1));
            $b = hexdec(substr($hex,2,1).substr($hex,2,1));
        } else {
            $r = hexdec(substr($hex,0,2));
            $g = hexdec(substr($hex,2,2));
            $b = hexdec(substr($hex,4,2));
        }
        return array($r, $g, $b); // Returns an array with the rgb values
    }

    static function getImageColor($hex, $img) {
        list($r, $g, $b) = self::getRgba($hex);
        return imagecolorallocate($img, $r, $g, $b);//定义一个颜色以后用
    }


    public static function generateShare($md5, $params = []){
        $imgSize = getimagesize(base_path() . "/public/uploads/share_bg.png"); //图片高宽
        try {
            $img = imagecreatefrompng(base_path() . "/public/uploads/share_bg.png");
        } catch (\Exception $e) {
            $img = imagecreatefromjpeg(base_path() . "/public/uploads/share_bg.png");
        }
        $fontSize = 25;
        $fontFile = base_path() . "/public/ttfs/5.ttf";
        $imageColor = self::getImageColor("#000", $img);//定义一个颜色以后用

        //小程序码
        $wxSize = getimagesize($params["wxQrCode"]); //图片高宽
        try{
            $tempImg = imagecreatefrompng($params["wxQrCode"]);
        }catch (\Exception $e){
            $tempImg = imagecreatefromjpeg($params["wxQrCode"]);
        }
        $wxNewSize = 150;
        $tempHeight = $wxNewSize + 30;
        $wxNewImg = imagecreatetruecolor($wxNewSize, $wxNewSize); //新建画布
        imagecopyresampled($wxNewImg, $tempImg, 0, 0, 0, 0, $wxNewSize, $wxNewSize, $wxSize[0], $wxSize[1]); //复制图片并调整大小
        imagedestroy($tempImg); //销毁
        imagecopy($img, $wxNewImg, floor($imgSize[0] / 10), $imgSize[1] - $tempHeight, 0, 0, $wxNewSize, $wxNewSize); //图片合并
        imagedestroy($wxNewImg);
        $text = "长按识别二维码";
        imagettftext($img, $fontSize, 0, floor($imgSize[0] / 10) + $wxNewSize + 10, $imgSize[1] - $wxNewSize / 2 - 35, $imageColor, $fontFile, $text);
        $text = "识别二维码后立即播放";
        imagettftext($img, $fontSize, 0,  floor($imgSize[0] / 10) + $wxNewSize + 10, $imgSize[1] - $wxNewSize / 2 + 5, $imageColor, $fontFile, $text);

        $text = "我正在看这个视频，推荐你来看看";
        $box = imagettfbbox($fontSize, 0, $fontFile, $text);
        $tempHeight = $tempHeight + 40;
        imagettftext($img, $fontSize, 0,  floor($imgSize[0] / 2) - floor(($box[2]-$box[0]) / 2), $imgSize[1] - $tempHeight, $imageColor, $fontFile, $text);
        $fontSize = 35;
        $text = $params["nickname"];
        $tempHeight = $tempHeight + 40;
        $box = imagettfbbox($fontSize, 0, $fontFile, $text);
        imagettftext($img, $fontSize, 0, floor($imgSize[0] / 2) - floor(($box[2]-$box[0]) / 2), $imgSize[1] - $tempHeight, $imageColor, $fontFile, $text);
        $userSize = getimagesize($params["avatar"]); //图片高宽
        try{
            $userImg = imagecreatefrompng($params["avatar"]);
        }catch (\Exception $e){
            $userImg = imagecreatefromjpeg($params["avatar"]);
        }
        $userNewSize = 120;
        $userNewImg = imagecreatetruecolor($userNewSize, $userNewSize);
        $userNewImgPha = imagecolorallocate($userNewImg, 0, 0, 0);//拾取一个颜色
        imagecolortransparent($userNewImg,$userNewImgPha); //变成完全透明的
        imagecopyresampled($userNewImg, $userImg, 0, 0, 0, 0, $userNewSize, $userNewSize, $userSize[0], $userSize[1]); //复制图片并调整大小
        imagedestroy($userImg);
        $userColor = imagecolorallocate($userNewImg, 255, 255, 255);
        imagearc($userNewImg, $userNewSize / 2, $userNewSize / 2, $userNewSize, $userNewSize, 180, 270, $userColor); //画左上角圆弧
        imagefilltoborder($userNewImg, 0, 0, $userColor, $userNewImgPha); //左上角
        imagearc($userNewImg, $userNewSize / 2, $userNewSize / 2, $userNewSize, $userNewSize, 90, 180, $userColor); //画左下角圆弧
        imagefilltoborder($userNewImg, 0, $userNewSize, $userColor, $userNewImgPha); //左下角
        imagearc($userNewImg, $userNewSize / 2, $userNewSize / 2, $userNewSize, $userNewSize, 0, 90, $userColor); //画左下角圆弧
        imagefilltoborder($userNewImg, $userNewSize, $userNewSize, $userColor, $userNewImgPha); //左下角
        imagearc($userNewImg, $userNewSize / 2, $userNewSize / 2, $userNewSize, $userNewSize, 270, 360, $userColor); //画左下角圆弧
        imagefilltoborder($userNewImg, $userNewSize, 0, $userColor, $userNewImgPha); //左下角
        $tempHeight = $tempHeight + $userNewSize + 40;
        imagecopy($img, $userNewImg, floor($imgSize[0] / 2)-floor($userNewSize/2), $imgSize[1] - $tempHeight, 0, 0, $userNewSize, $userNewSize); //图片合并
        imagedestroy($userNewImg);

        $text = $params["title"];
        // 为了换行
        $box = imagettfbbox($fontSize, 0, $fontFile, $text);
        if($box[2] > $imgSize[0]){
            $tempText = '';
            $i = 0;
            $newText = [];
            do{
                $temp = mb_substr($text, $i, 1);
                $tempText .= $temp;
                $i++;
                $box = imagettfbbox($fontSize, 0, $fontFile, $tempText);
                $cycle = $temp ? true : false;
                if($box[2] + 100 >= $imgSize[0]){
                    $newText [] = $tempText;
                    if(mb_substr($text, mb_strlen($tempText))){
                        $text = mb_substr($text, mb_strlen($tempText));
                        $i = 0;
                        $tempText = '';
                    }else {
                        $cycle = false;
                    }
                }elseif(!$cycle && $tempText){
                    $newText [] = $tempText;
                }
                if(count($newText) >= 2){
                    $cycle = false;
                }
            }while(!empty($cycle));
            $newText = array_reverse($newText);
            foreach ($newText as $key => $item){
                $box = imagettfbbox($fontSize, 0, $fontFile, $item);
                $tempHeight = $tempHeight + ($box[1]+abs($box[7]));
                imagettftext($img, $fontSize, 0, floor($imgSize[0] / 2) - floor(($box[2]-$box[0]) / 2), $imgSize[1] - $tempHeight, $imageColor, $fontFile, $item);
            }
        }else {
            $box = imagettfbbox($fontSize, 0, $fontFile, $text);
            $tempHeight = $tempHeight + $box[1]+abs($box[7]);
            imagettftext($img, $fontSize, 0, floor($imgSize[0] / 2) - floor(($box[2]-$box[0]) / 2), $imgSize[1] - $tempHeight, $imageColor, $fontFile, $text);
        }

        if(!empty($params["coverImgUrl"])){
            $coverImg = $params["coverImgUrl"];
        }else {
            $coverImg = "https://1251017581.vod2.myqcloud.com/3eb03e26vodtransgzp1251017581/990a69d15285890805449534049/coverBySnapshot/1595241369_2503165012.100_0.jpg";
        }
        try {
            $tempImg = imagecreatefrompng($coverImg);
        } catch (\Exception $e) {
            $tempImg = imagecreatefromjpeg($coverImg);
        }
        $tempImgSize = getimagesize($coverImg); //图片高宽
        if($tempImgSize[0] < $tempImgSize[1]){
            $y = floor(($tempImgSize[1] - ($imgSize[1] - $tempHeight - 50)) / 2);
            imagecopyresampled($img, $tempImg, 0, 0, 0, $y, $imgSize[0], $imgSize[1] - $tempHeight - 50, $tempImgSize[0], $imgSize[1] - $tempHeight - 50); //复制图片并调整大小
        }else {
            imagecopyresampled($img, $tempImg, 0, 0, 0, 0, $imgSize[0], $imgSize[1] - $tempHeight - 50, $tempImgSize[0], $tempImgSize[1]); //复制图片并调整大小
        }

        // 字体颜色
        list($r, $g, $b) = self::getRgba("#fff");
        $tempColor = imagecolorallocate($img, $r, $g, $b);//定义一个颜色以后用
        $text = "热度：".(isset($params["viewCount"]) ? $params["viewCount"] : 0);
        $box = imagettfbbox($fontSize, 0, $fontFile, $text);
        imagettftext($img, $fontSize, 0, $imgSize[0] - $box[2] - $box[0] - 15, $imgSize[1] - $tempHeight - 50 - $box[1] - abs($box[7]), $tempColor, $fontFile, $text);

        ob_start();
        // 输出图像
        imagejpeg($img);
        $content = ob_get_clean();
        imagedestroy($img);
//        return response($content, 200, ['Content-Length' => strlen($content), 'Content-Type' => "image/png; charset=utf-8"]);
        global $scf_data;
        if(!empty($scf_data["IS_SCF"])) { // 云开发
            $object = new Picture();
            $result = $object->uploadImg($md5."_sharePic.png", $content);
            return $result['ObjectURL'];
        }else {
            file_put_contents(base_path() . "/public/attachment/wxapp/{$md5}_sharePic.png", $content);
            if(basename($_SERVER["DOCUMENT_ROOT"]) != "public"){ // 根目录运行
                return request()->getSchemeAndHttpHost()."/public/attachment/wxapp/{$md5}_sharePic.png?t=".time();
            }else{
                return request()->getSchemeAndHttpHost()."/attachment/wxapp/{$md5}_sharePic.png?t=".time();
            }
        }
    }

    //处理图片路径
    static function processingPictures($url){
        if (!$url){
            return $url;
        }
        global $scf_data;
        //去除路径一个点的字符
        if(substr($url,0,1) == '.'){
            $url = substr($url,1,(strlen($url)-1));
        }
        if(substr($url,0,1) != '/' && substr($url,0,1) != 'h'){
            $url = '/'.$url;
        }
//        if(strstr($url,"http://") && $scf_data['IS_SCF'] == true){
//            $url = str_ireplace('http://','https://',$url);
//        }
        if(!strstr($url,"http")){
            if ($scf_data['IS_SCF'] == true) {
                $host = 'https://'.$scf_data['system']['bucketConfig']['bucket'].'.cos.'.$scf_data['system']['bucketConfig']['region'].'.myqcloud.com';
                $url = $host.$url;
            }else{
                $path = $_SERVER['DOCUMENT_ROOT'];//获取网站根目录
                if (strstr($path,'public')){
                    $url = $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER['SERVER_NAME'].$url;
                }else{
                    $url = $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER['SERVER_NAME'].'/public'.$url;
                }
            }
        }
        return $url;
    }

    /* 数组排序 */
    public static function array_sort($array, $column, $sort = 'SORT_ASC')
    {
        $new_array = array();
        $sort_array = array();
        foreach ($array as $key => $value) {
            if (!is_array($value)) {
                $sort_array[$key] = $value;
            } else {
                if(isset($value[$column])){
                    $sort_array[$key] = $value[$column];
                }
            }
        }
        switch ($sort) {
            case 'SORT_ASC':
                asort($sort_array);
                break;
            case 'SORT_DESC':
                arsort($sort_array);
                break;
        }
        foreach ($sort_array as $key => $value) {
            $new_array[$key] = $array[$key];
        }
        return $new_array;
    }
}